
package uk.org.cardboardbox.nfcpointstracker;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.IOException;

public class CameraUtils {

    private static final String TAG = CameraUtils.class.getCanonicalName();

    @SuppressLint("WorldWriteableFiles")
    public static File getTempImageFile(Context context) {
        File tempFile = new File(context.getFilesDir(), "phototemp"
                + Long.toString(System.currentTimeMillis()) + ".jpg");

        if (!tempFile.exists()) {
            try {
                context.openFileOutput(tempFile.getName(), Context.MODE_WORLD_WRITEABLE).close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        Log.d(TAG, "temp file is: " + tempFile.getAbsolutePath());
        return tempFile;
    }

    public static void takePhoto(BaseActivity activity, File output) {
        Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
        activity.startActivityForResult(i, BaseActivity.REQUESTCODE_TAKEPHOTO);
    }

    public static void cropPhoto(BaseActivity activity, File input, File output) {
        try {
            Runtime.getRuntime().exec("chmod 777 " + input.getAbsolutePath());
            Runtime.getRuntime().exec("chmod 777 " + output.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        final Uri inputPhotoUri = Uri.fromFile(input);
        final Uri croppedPhotoUri = Uri.fromFile(output);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(inputPhotoUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 128);
        intent.putExtra("outputY", 128);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, croppedPhotoUri);
        activity.startActivityForResult(intent, BaseActivity.REQUESTCODE_CROP);
    }
}
